package com.cdtu.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cdtu.entity.Modules;
import com.cdtu.service.ModulesService;
import com.cdtu.vo.AdminModulesVo;
import com.cdtu.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@Slf4j
@RestController
//解决跨域问题
@CrossOrigin
@RequestMapping("/auth")
public class AuthorityController {

    @Autowired
    ModulesService modulesService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/model")
    public R getModules(long id,String to){
        if(to.contains("/user/UserDetail")){
            return R.success();
        }
        List<AdminModulesVo> arrayList =null;
        String s = redisTemplate.opsForValue().get("auth:" + id);
        arrayList = JSONUtil.toList(s, AdminModulesVo.class);
        if (StrUtil.hasBlank(s)){
            arrayList= modulesService.getModules(id);
            String s1 = JSONUtil.toJsonStr(arrayList);
            redisTemplate.opsForValue().set("auth:"+id,s1);
        }
        for (AdminModulesVo adminModulesVo : arrayList) {
            Optional<Modules> any = adminModulesVo.getChild().stream().filter(i -> i.getPath().equals(to)).findAny();
            if (any.isPresent()){
                return R.success();
            }
            else R.error("无权限");
        }
        return R.error("无权限");
    }

}
